package com.innovatio.validator.handlers;

import com.innovatio.utils.general.CommonsUtils;
import com.innovatio.utils.bean.BeanExpresionEvaluator;
import com.innovatio.validator.Validable;
import com.innovatio.validator.ValidationErrors;
import com.innovatio.validator.annotations.ValidateRequired;
import com.innovatio.validator.exceptions.ValidatorException;
import org.apache.commons.beanutils.BeanUtils;

/**
 * This code is property of Innovatio SOftware Solutions, Inc.
 * User: Ramon
 * Date: Mar 4, 2009
 * Time: 11:01:47 AM
 */
public class ValidateRequiredHandler implements ValidationHandler<ValidateRequired> {

    public ValidationErrors.Error validate(ValidateRequired annotation, Validable container, String fieldName, String value) throws ValidatorException {

        boolean isrequried = true;


        String field = annotation.ifFieldIsEmpty();
        if (!field.equals(CommonsUtils.EMPTY)) {
            String v = getFieldValue(container, field);
            if (CommonsUtils.isStringEmpty(v))
                    isrequried = false;

        }

        field = annotation.ifFieldIsNotEmpty();
        if (!field.equals(CommonsUtils.EMPTY)) {
            String v = getFieldValue(container, field);
            if (CommonsUtils.isStringEmpty(v))
                    isrequried = false;
        }

        field = annotation.ifFieldValueEquals();
        if (!field.equals(CommonsUtils.EMPTY)) {

            try {
                Boolean b = BeanExpresionEvaluator.newInstance(container, field).evaluate();
                if (!b) {
                    isrequried = false;
                }

            } catch (Exception e) {
                throw new ValidatorException(e);
            }

        }

        if (isrequried  && CommonsUtils.isStringEmpty(value)) {
            return new ValidationErrors.Error(fieldName, annotation.i18nBundleKey());
        }

        return null;
    }


    private String getFieldValue(Validable v, String field) throws ValidatorException {
        String va = null;
        try {
            va = BeanUtils.getSimpleProperty(v, field);
        } catch (Exception e) {
            throw new ValidatorException(e);
        }
        return va;
    }

}